<template>
  <div class="upload-img">
    <el-upload
      class="avatar-uploader"
      action="https://jsonplaceholder.typicode.com/posts/"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img v-if="value" v-errorimg :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- 删除图标 -->
    <i v-if="value" class="el-icon-delete del" @click="delEvent" />
    <!-- 放大图标 -->
    <i v-if="value" class="el-icon-zoom-in big" @click="show=true" />
    <!-- 大图片预览弹框 -->
    <el-dialog title="图片预览" :visible.sync="show" width="700px">
      <img style="width:100%;" :src="value" alt="">
    </el-dialog>
    <!-- 上传进度 条 -->
    <transition name="xxx">
      <el-progress v-if="showProgress" :width="178" class="progress" type="circle" :percentage="percentage" />
    </transition>
  </div>

</template>
<script>
import COS from 'cos-js-sdk-v5'
var cos = new COS({
  SecretId: 'AKIDNXR8bpeSF1JL8EyZopxRfdHgqGUeuEn8',
  SecretKey: 'HJ9mAbQEn7jgjY9swEI6yAamk7MN8hty'
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imageUrl: '',
      show: false,
      showProgress: false,
      percentage: 0
    }
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG ,PNG格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    // 自定义上传
    httpRequest(res) {
      const file = res.file
      // 显示进度 条
      this.showProgress = true
      cos.uploadFile({
        Bucket: 'abc-1305249343', /* 填写自己的 存储桶，必须字段 */
        Region: 'ap-chongqing', /* 存储桶所在地域，必须字段 */
        Key: '94hr/' + file.name, /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */
        Body: file, // 上传文件对象
        SliceSize: 1024 * 1024 * 0.5, /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */
        onProgress: (progressData) => {
          this.percentage = +(progressData.percent * 100).toFixed(2)
          if (progressData.percent === 1) {
            setTimeout(() => {
              this.showProgress = false
            }, 1000)
          }
          console.log(JSON.stringify(progressData))
        }
      }, (err, data) => {
        if (err) {
          console.log('上传失败', err)
        } else {
          console.log('上传成功', data)
          //   this.value = 'http://' + data.Location
          this.$emit('input', 'http://' + data.Location)
        }
      })
    },
    // 删除点击
    async delEvent() {
      await this.$confirm('您确定删除该图片吗')
      this.$emit('input', '')
      this.$message.success('删除成功')
    }
  }
}
</script>
<style lang="scss" scoped>
  .avatar-uploader ::v-deep .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader ::v-deep  .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
    object-fit: contain;
  }
  .upload-img{
    position: relative;
    width: 178px;
    height: 178px;
    &:hover{
        .del,.big{
            display: block;
            color:red;
        }
    }
    .del,.big{
        position: absolute;
        top:5px;
        right:5px;
        display: none;
        font-size: 20px;
        cursor: pointer;
    }
    .big{
        right:30px
    }
    .progress{
        position: absolute;
        left:1px;
        top:1px;
        background-color: #fff;
    }
  }

  .xxx-enter-active,.xxx-leave-active{
    transition: all 0.5s;
  }
  .xxx-enter,.xxx-leave-to{
    opacity: 0;
  }

</style>
